package org.hishenframework.core.web.message.interceptor;

import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hishenframework.core.web.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class MessageInterceptor extends HandlerInterceptorAdapter {

	protected Logger logger = LoggerFactory.getLogger(MessageInterceptor.class);

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		//handler是object型的，所以要验证
		if (!(handler instanceof HandlerMethod)) {
			logger.debug("handler are not org.springframework.web.method.HandlerMethod");
			return;
		}
		
		//只处理ModelAndView中有Message类，和methodNames中包含给方法名的方法
		Message message = null;
		message = (Message) modelAndView.getModel().get("message");
		
		if (message == null) {
			return;
		}
		
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		String methodName = handlerMethod.getMethod().getName();
		if (message.getMethodName() == null) {
			message.setMethodName(methodName);
		}
		
		for (Entry<String, Object> entry : modelAndView.getModel().entrySet()) {
			if (!entry.getKey().equals("org.springframework.validation.BindingResult.message")
					&& entry.getValue() instanceof BeanPropertyBindingResult) {
				//TODO: 多result，验证详细信息
				message.setResult((BindingResult) entry.getValue());
				break;
			}
		}
		//建立消息
		message.build();
		
		HttpSession session = request.getSession();
		session.setAttribute("message", message);
		
	}

}
